# -*- coding: utf-8 -*-
"""
Created on Wed Feb 16 19:38:27 2022

@author: 22155
"""

import pickle
import tensorflow.compat.v1 as tf
import numpy as np
import pandas as pd

class Play:    
    def load_ scenarys_matrics(self):
        """
        从文件中加载参数
        """
        return pickle.load(open('D:\\tmp\\goodluck\\goodluck\\luck\\scenary_matrics.p', mode='rb'))
        
    def get_tensors(self,loaded_graph):
        '''
        从 loaded_graph 中获取tensors
        '''
        user_gender = loaded_graph.get_tensor_by_name("user_gender:0")
        user_age = loaded_graph.get_tensor_by_name("user_age:0")
        user_job = loaded_graph.get_tensor_by_name("user_job:0")
        user_area = loaded_graph.get_tensor_by_name("user_area:0")
        user_ft = loaded_graph.get_tensor_by_name("user_ft:0")
        
        scenary_id = loaded_graph.get_tensor_by_name(" scenary_id:0")
         scenary_categories = loaded_graph.get_tensor_by_name(" scenary_categories:0")
        targets = loaded_graph.get_tensor_by_name("targets:0")
        dropout_keep_prob = loaded_graph.get_tensor_by_name("dropout_keep_prob:0")
        lr = loaded_graph.get_tensor_by_name("LearningRate:0")
        inference = loaded_graph.get_tensor_by_name("inference/ExpandDims:0")
         scenary_combine_layer_flat = loaded_graph.get_tensor_by_name(" scenary_fc/Reshape:0")
        user_combine_layer_flat = loaded_graph.get_tensor_by_name("user_fc/Reshape:0")
        return user_gender, user_age, user_job, user_area, user_ft, scenary_id,  scenary_categories, targets, lr, dropout_keep_prob, inference,  scenary_combine_layer_flat, user_combine_layer_flat
    
    
        
    def tfrun(self,data):
        '''
        运行模型 计算用户特征矩阵
        根据用户特征矩阵和景点特征矩阵计算出最佳的n个景点
        '''
         scenary_matrics = self.load_ scenarys_matrics()        
        loaded_graph = tf.Graph()
        
        
        self.res = []
        self.sss = []
        aaa = {}
        citys = ["北京","上海","重庆","天津","厦门","福州","泉州","南平","宁德","杭州","宁波","台州","湖州"\
                 ,"南京","苏州","扬州","无锡","连云港","南通","青岛","济南","合肥","黄山","大连","沈阳","石家庄"\
                 ,"哈尔滨","太原","呼和浩特","呼伦贝尔","长春","三亚","海口","广州","深圳","珠海","长沙","武汉"\
                 ,"宜昌","成都","昆明","大理","宝鸡","拉萨","兰州","乌鲁木齐","遵义","银川"]
        

        # 从字典中获取相应的数据
        city = data.get('city')
        time = data.get('time')
        busy = data.get('busy')
        
        occupation = data.get('occupation')
        genre = data.get('genre')
        age = data.get('age')
        gender = data.get('gender')
        region = data.get('region')
        print(data)
    
        city = citys[int(city)]
        

        # 数据测试
        # city = '北京'
        # time = 0
        # busy = 2
        
        # occupation = 2
        # genre = 4
        # age = 3
        # gender = 1
        # region =0
        
        # 读取景点数据 根据所选城市筛选景点
        scenary_title = ['sid','sname', 'area','picture','jianjie', 'jinweidu']
        scenary = pd.read_table('D:\\tmp\\goodluck\\goodluck\\luck\\fff.txt', sep=':', header=None, names=scenary_title, engine = 'python')
        scenary = scenary.filter(regex='sid|sname|area')
        scenary = scenary[scenary.area == city]
        
        sset = set(scenary['sid'])
        
        num = (time+3)*(busy+1)+4

        with tf.Session(graph=loaded_graph) as sess:
            # 载入保存好的模型
            loader = tf.train.import_meta_graph('D:\\tmp\\goodluck\\goodluck\\luck\\save.meta')
            loader.restore(sess , 'D:\\tmp\\goodluck\\goodluck\\luck\\save')
        
            # 调用函数拿到 tensors
            user_gender, user_age, user_job, user_area, user_ft,  scenary_id,  scenary_categories, targets, lr, dropout_keep_prob, _, __,user_combine_layer_flat = self.get_tensors(loaded_graph)  #loaded_graph
            
            # 输入用户基本特征
            feed = {
                user_gender: [[gender]],
                user_age: [[age]],
                user_job: [[occupation]],
                user_area: [[region]], 
                user_ft: [[genre,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 0,  0, 0,  0]],
                dropout_keep_prob: 1}
            # 得到用户特征矩阵
            user_combine_layer_flat_val = sess.run([user_combine_layer_flat], feed) 
        
        a = np.array(user_combine_layer_flat_val)
        a = a.reshape(1,-1)
        # 用户特征矩阵*电影特征矩阵-->预测评分
        c = a.dot( scenary_matrics.T)
        
        c = c.reshape(-1)
        # self.res 预测评分排序后的索引序列 评分从小到大排序
    
        ress = np.argsort(c)
        ress = list(filter(lambda x: x in sset, ress))


        self.res = ress[-num:-1]
        print("self.res",self.res)
        for i in self.res:
            # aaa = scenary[scenary.sid == i]
            # aaa = aaa["sname"]
            ind = scenary.loc[scenary['sid'] == i]
            # print(ind)
            ind = ind.index[0]
            aaa = scenary.at[ind,"sname"]
            print(aaa)
            self.sss.append(aaa)
        # print(self.sss)
            
            
    

# 代码测试
# a = Play()
# a.tfrun()
# print(a.sss)    
    
